9  R: Functions

9.1 Defining a function

Functions in R are defined using the keyword function(). All the statements within a function are enclosed with {} braces. Look at the function defined below. It takes an integer as an argument, and prints whether the integer is odd or even.

odd_even<-function(intgr)
{
  if(intgr%%2==0)
  {
    print("even")}else{
      print("odd")
  }
}

odd_even(3)
[1] "odd"

9.1.1 Practice exercise

Write a function that returns all prime numbers between \(a\) and \(b\), where \(a\) and \(b\) are parameters of the function.